package cn.bellychang.ood.mailsendproduct.good;

import cn.bellychang.ood.mailsendproduct.Configuration;
import cn.bellychang.ood.mailsendproduct.ConfigurationKeys;
import cn.bellychang.ood.mailsendproduct.MailUtil;

/**
 * @author ChangLiang
 * @date 2020/5/12
 */
public class MailSender {

    private String fromAddress;
    private String smtpHost;
    private String alternativeSmtpHost;

    public MailSender(Configuration config) {
        this.fromAddress = config.getProperty(ConfigurationKeys.EMAIL_ADMIN);
        this.smtpHost = config.getProperty(ConfigurationKeys.SMTP_SERVER);
        this.alternativeSmtpHost = config.getProperty(ConfigurationKeys.ALTERNATIVE_SMTP_SERVER);
    }

    public void sendMail(Mail mail) {
        try {
            sendEmail(mail, this.smtpHost);
        } catch (Exception e) {
            try {
                sendEmail(mail, this.alternativeSmtpHost);
            } catch (Exception ex) {
                System.out.println("通过备用SMTP服务器发送邮件失败: " + ex.getMessage());
            }

        }
    }

    private void sendEmail(Mail mail, String smtpHost) {
        String toAddress = mail.getAddress();
        String subject = mail.getSubject();
        String message = mail.getBody();
        //发送邮件
        MailUtil.sendEmail(toAddress, fromAddress, subject, message, smtpHost, false);
    }
}
